﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Filters;

namespace EMSystem.WebSite.Filter
{
    public class CheckLoginStateAttribute : FilterAttribute, IAuthenticationFilter
    {
        private string _SessionKey = "UserApp";
        public string SessionKey
        {
            get
            {
                return _SessionKey;
            }
            set
            {
                _SessionKey = value;
            }
        }

        public CheckLoginStateAttribute() { }

        public CheckLoginStateAttribute(string SessionKey)
        {
            this.SessionKey = SessionKey;
        }

        public void OnAuthentication(AuthenticationContext filterContext)
        {
            var user = filterContext.HttpContext.Session[_SessionKey];
            if (user == null)
            {
                var Url = new UrlHelper(filterContext.RequestContext);
                var url = Url.Action("Login", "home", new { area = "" });
                filterContext.Result = new RedirectResult(url);
            }
        }
        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
            //这个方法是在Action执行之后调用
        }
    }
}